package com.clark.dingding.retrofit

import android.os.Build
import android.util.Log
import com.clark.dingding.constants.ApiConstants
import com.linkage.linkedlife.BuildConfig
import com.linkage.linkedlife.retrofit.CookieHandler
import com.linkage.linkedlife.retrofit.HttpLoggingInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okio.Utf8
//import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.UTFDataFormatException
import java.lang.StringBuilder
import java.nio.charset.Charset
import java.util.*

object ApiClient {


    /**
     * 获取指定数据类型
     * @return
     */
    @JvmStatic
    val gankDataService: GankDataService
        get() = initService(ApiConstants.GankHost, GankDataService::class.java)


    /**
     * 动态url获取数据
     * @return
     */
    @JvmStatic
    val dynamicDataService: DynamicApiService<*>
        get() = initService("", DynamicApiService::class.java)


    /**
     * 获得想要的 retrofit service
     * @param baseUrl  数据请求url
     * @param clazz    想要的 retrofit service 接口，Retrofit会代理生成对应的实体类
     * @param <T>      api service
     * @return
    </T> */
    private fun <T> initService(baseUrl: String, clazz: Class<T>): T {
        return retrofitInstance!!.create(clazz)
    }

    /**单例retrofit */
    private var retrofitInstance: Retrofit? = null
        private get() {
            if(field==null){
            synchronized(ApiClient::class.java){
                if(field==null){
                    field=Retrofit.Builder()
                        .baseUrl(ApiConstants.GankHost)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .client(getOkHttpClientInstance())
                        .build()
                }
            }

        }
            return field;
    }

    /**单例OkHttpClient */
    private var okHttpClientInstance: OkHttpClient? = null
    private fun getOkHttpClientInstance(): OkHttpClient? {
        if (okHttpClientInstance == null) {
            synchronized(ApiClient::class.java) {
                if (okHttpClientInstance == null) {
                    val builder = OkHttpClient().newBuilder()
                    if (BuildConfig.DEBUG) {
                        val httpLoggingInterceptor = HttpLoggingInterceptor()
                        val headInterceptor = HeadInterceptor()
                        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
                        builder.addInterceptor(httpLoggingInterceptor)
//                            .addInterceptor(headInterceptor)
                        //                      builder.addNetworkInterceptor(new StethoInterceptor());
//                      BuildConfig.STETHO.addNetworkInterceptor(builder);
                    }
                    okHttpClientInstance = builder.build()
                }
            }
        }
        return okHttpClientInstance
    }


    class HeadInterceptor : Interceptor {
        private var _UTF8: Charset = Charset.forName("UTF-8")
        override fun intercept(chain: Interceptor.Chain): Response {
            var request = chain.request()
            var newRequest = request.newBuilder()
                .addHeader("Content-Language", "zh-CN")
                .addHeader("Accept-Language", "zh-CN")
                .addHeader("Platform", "android")
                //版本号
                .addHeader("Version", BuildConfig.VERSION_NAME)
                //时区   值:Asia/Shanghai
                .addHeader("TimeZone", TimeZone.getDefault().getID())
                //型号
                .addHeader("Model", Build.MODEL)
                //SDK版本1
                .addHeader("SDKVersion", Build.VERSION.RELEASE)
                .build();
            var headers = request.headers
            var headerListMap = headers.toMultimap()
            for (element in headerListMap) {
                var values = element.value
                var sb = StringBuilder()
                for (element in values) {
                    sb.append(element).append(" ")
                }
            }
            var proceed = chain.proceed(newRequest)


            var responseBody = proceed.body!!
            var source = responseBody.source()
            source.request(Long.MAX_VALUE)
            var buffer = source.buffer
            var charset = _UTF8
            var contentType = responseBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(_UTF8)!!
            }
            if (responseBody.contentLength() != 0L) {
                Log.d(
                    "clark",
                    request.toString() + "app-------响应内容：" + buffer.clone().readString(charset)
                )

            }
            var host = request.url.host
            CookieHandler.processResponseCookie(proceed, host)


            return proceed


        }

    }
}
//获取指定地址的网络连接



